package com.qintingfm.bootstrapdownload.download;

import com.qintingfm.bootstrapdownload.exceptions.HttpExceptions;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author guliuzhong
 */
@Slf4j
public class DownLoadServer {
    DownConfig downConfig;
    private final String[][] MIME_MapTable = {
            {".3gp", "video/3gpp"},
            {".apk", "application/vnd.android.package-archive"},
            {".asf", "video/x-ms-asf"},
            {".avi", "video/x-msvideo"},
            {".bin", "application/octet-stream"},
            {".bmp", "image/bmp"},
            {".c", "text/plain"},
            {".class", "application/octet-stream"},
            {".conf", "text/plain"},
            {".cpp", "text/plain"},
            {".css", "text/css"},
            {".doc", "application/msword"},
            {".exe", "application/octet-stream"},
            {".gif", "image/gif"},
            {".gtar", "application/x-gtar"},
            {".gz", "application/x-gzip"},
            {".h", "text/plain"},
            {".htm", "text/html"},
            {".html", "text/html"},
            {".ico", "image/x-icon"},
            {".jar", "application/java-archive"},
            {".java", "text/plain"},
            {".jpeg", "image/jpeg"},
            {".jpg", "image/jpeg"},
            {".js", "application/x-javascript"},
            {".json", "application/json"},
            {".log", "text/plain"},
            {".m3u", "audio/x-mpegurl"},
            {".m4a", "audio/mp4a-latm"},
            {".m4b", "audio/mp4a-latm"},
            {".m4p", "audio/mp4a-latm"},
            {".m4u", "video/vnd.mpegurl"},
            {".m4v", "video/x-m4v"},
            {".mov", "video/quicktime"},
            {".mp2", "audio/x-mpeg"},
            {".mp3", "audio/x-mpeg"},
            {".mp4", "video/mp4"},
            {".mpc", "application/vnd.mpohun.certificate"},
            {".mpe", "video/mpeg"},
            {".mpeg", "video/mpeg"},
            {".mpg", "video/mpeg"},
            {".mpg4", "video/mp4"},
            {".mpga", "audio/mpeg"},
            {".msg", "application/vnd.ms-outlook"},
            {".ogg", "audio/ogg"},
            {".pdf", "application/pdf"},
            {".png", "image/png"},
            {".pps", "application/vnd.ms-powerpoint"},
            {".ppt", "application/vnd.ms-powerpoint"},
            {".prop", "text/plain"},
            {".rar", "application/x-rar-compressed"},
            {".rc", "text/plain"},
            {".rmvb", "audio/x-pn-realaudio"},
            {".rtf", "application/rtf"},
            {".sh", "text/plain"},
            {".svg", "image/svg+xml"},
            {".tar", "application/x-tar"},
            {".tgz", "application/x-compressed"},
            {".txt", "text/plain"},
            {".wav", "audio/x-wav"},
            {".wma", "audio/x-ms-wma"},
            {".wmv", "audio/x-ms-wmv"},
            {".wps", "application/vnd.ms-works"},
            {".xml",    "text/xml"},
            //{".xml", "text/plain"},
            {".z", "application/x-compress"},
            {".zip", "application/zip"},
            {"", "*/*"}
    };

    public DownLoadServer(DownConfig downConfig) {
        this.downConfig = downConfig;
    }

    public void downRequest(HttpServletRequest request, OutputStream outputStream) throws IOException ,HttpExceptions{
        InputStream inputStream = cacheToFile(request);
        inputStream.transferTo(outputStream);
    }
    public InputStream cacheToFile(HttpServletRequest request) throws IOException ,HttpExceptions{
        String requestURI = request.getRequestURI();
        String root=downConfig.getLocalPath()+"/"+downConfig.getName();
        if (Files.exists(Path.of(root+requestURI))){
            InputStream inputStream = Files.newInputStream(Paths.get(root+requestURI));
            return inputStream;
        }

        String url=downConfig.baseUrl+(request.getRequestURI());
        log.info("request url"+url);
        OkHttpClient client = new OkHttpClient();
        Request request1 = new Request.Builder().url(url).build();
        Response execute = client.newCall(request1).execute();
        if(execute.isSuccessful()){
            Path of = Path.of(root+requestURI);
            Files.createDirectories(of.getParent());
            execute.body().byteStream().transferTo(Files.newOutputStream(Path.of(root+requestURI)));
            InputStream inputStream = Files.newInputStream(Paths.get(root+requestURI));
            return inputStream;
        }else{
            execute.close();
            throw new HttpExceptions(execute.message(),execute.code());
        }
    }
    /**
     * 根据文件后缀名获得对应的MIME类型。
     * @param file
     */
    public String getMIMEType(String file)
    {
        String type="*/*";
        String fName=file;
        //获取后缀名前的分隔符"."在fName中的位置。
        int dotIndex = fName.lastIndexOf(".");
        if(dotIndex < 0){
            return type;
        }
        /* 获取文件的后缀名 */
        String end=fName.substring(dotIndex,fName.length()).toLowerCase();
        if(end=="") {
            log.warn("{} default mime:{}",file,type);
            return type;
        }
        //在MIME和文件类型的匹配表中找到对应的MIME类型。
        for(int i=0;i<MIME_MapTable.length;i++){
            if(end.equals(MIME_MapTable[i][0])) {
                type = MIME_MapTable[i][1];
            }
        }
        log.warn("{}mime:{}",file,type);
        return type;
    }
}
